<?php

namespace app\admin\command;

use app\admin\model\shopro\ThirdOauth;
use app\common\library\RabbitMQ as RabbitMQLibrary;
use app\common\model\User;
use fast\Random;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;

class RabbitMq extends Command
{
    // 进程ID文件路径
//    protected $pidFile = '/tmp/rabbitmq_consumer.pid';
    protected $pidFile = 'public/rabbitmq_consumer.pid';
    protected function configure()
    {
        // 指令配置 - 支持多个操作
        $this->setName('rabbitmq')
            ->addArgument('action', Argument::OPTIONAL, '操作类型: start|stop|restart|status', 'start')
            ->setDescription('RabbitMQ消费者管理 (启动/停止/重启/状态查询)');
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        
        switch ($action) {
            case 'start':
                $this->startConsumer($output);
                break;
            case 'stop':
                $this->stopConsumer($output);
                break;
            case 'restart':
                $this->restartConsumer($output);
                break;
            case 'status':
                $this->checkStatus($output);
                break;
            default:
                $output->writeln('未知操作，支持的操作: start, stop, restart, status');
                break;
        }
    }
    
    /**
     * 启动消费者
     */
    protected function startConsumer(Output $output)
    {
        // 检查是否已经在运行
        if ($this->isRunning()) {
            $output->writeln('RabbitMQ消费者已经在运行中 (PID: ' . $this->getPid() . ')');
            return;
        }
        
        $output->writeln('正在启动RabbitMQ消费者...');
        
        try {
            // 创建RabbitMQ实例
            $rabbitMQ = new RabbitMQLibrary();
            
            // 保存进程ID
            $this->savePid(getmypid());
            
            // 启动消费者
            $rabbitMQ->consume(function ($message) use ($output) {
                // 处理接收到的消息
                $output->writeln('Received message: ' . json_encode($message, JSON_UNESCAPED_UNICODE));
                trace('消费队列参数: ' . json_encode($message, JSON_UNESCAPED_UNICODE));
                $data = $message['data'];
                $unionid = $data['unionid'];
                $score = $data['score'];
                $thirdOauth =  ThirdOauth::field('id,user_id')->where('unionid', $unionid)->find();

                if(!$thirdOauth){
                    $username = Random::alnum(8);
                    $password = 123456;
                    $email = $username . '@163.com';
                    $time = time();
                    $output->writeln('微信用户参数$time: ' . json_encode($time, JSON_UNESCAPED_UNICODE));
                    $salt =  Random::alnum();
                    $avatar  = 'https://tyhwshop.chaopinvideo.cn/uploads/20251119/b00ed95f39f0764c3b5ecbe3d6999d6e.png';
                    $userData = [
                        'username' => $username,
                        'password' => $password,
                        'email'    => $email,
                        'group_id'    => 1,
                        'level'    => 1,
                        'score'    => 0,
                        'avatar'   => $avatar,
                    ];
                    $output->writeln('微信用户参数$userData: ' . json_encode($userData, JSON_UNESCAPED_UNICODE));

                    $params = array_merge($userData, [
                        'nickname'  =>  '用户' . $username,
                        'salt'      => $salt,
                        'jointime'  => $time,
                        'joinip'    => '127.0.0.1',
                        'logintime' => $time,
                        'loginip'   => '127.0.0.1',
                        'prevtime'  => $time,
                        'status'    => 'normal'
                    ]);
                    $params['password'] =  md5(md5($password) . $salt);
                    $output->writeln('微信用户参数$params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));

                    $user = User::create($params);
                    $output->writeln('微信用户参数$user: ' . json_encode($user, JSON_UNESCAPED_UNICODE));

                    if ($user) {
                        $thirdOauth = ThirdOauth::create([
                            'user_id' => $user->id,
                            'openid' => '',
                            'unionid' => $unionid,
                            'provider' => 'wechat',
                            'platform' => 'miniProgram',
                            'nickname' => $unionid,
                            'avatar' => $avatar,
                            'createtime' => $time,
                            'updatetime' => $time
                        ]);
                        $output->writeln('微信用户参数$user1: ' . json_encode($thirdOauth, JSON_UNESCAPED_UNICODE));

                    }
                    $user_id = $user->id;
                }else{
                    $user_id = $thirdOauth['user_id'];
                }
                $output->writeln('微信用户userId: ' . $user_id);

                // 变更会员积分
                User::score($score, $user_id, '直播积分变更');
                return true;
            });
            
        } catch (\Exception $e) {
            $output->writeln('启动失败: ' . $e->getMessage());
            // 清理PID文件
            $this->cleanPidFile();
            return 1;
        }
        
        return 0;
    }
    
    /**
     * 停止消费者
     */
    protected function stopConsumer(Output $output)
    {
        if (!$this->isRunning()) {
            $output->writeln('RabbitMQ消费者未运行');
            return;
        }
        
        $pid = $this->getPid();
        if ($pid && posix_kill($pid, SIGTERM)) {
            $output->writeln('正在停止RabbitMQ消费者 (PID: ' . $pid . ')');
            // 等待进程结束
            sleep(2);
            if (!$this->isRunning()) {
                $output->writeln('RabbitMQ消费者已成功停止');
                $this->cleanPidFile();
            } else {
                // 强制终止
                posix_kill($pid, SIGKILL);
                $output->writeln('RabbitMQ消费者已强制终止');
                $this->cleanPidFile();
            }
        } else {
            $output->writeln('停止失败，请检查进程状态');
            $this->cleanPidFile();
        }
    }
    
    /**
     * 重启消费者
     */
    protected function restartConsumer(Output $output)
    {
        if ($this->isRunning()) {
            $this->stopConsumer($output);
            sleep(1); // 等待进程完全停止
        }
        
        $this->startConsumer($output);
    }
    
    /**
     * 检查状态
     */
    protected function checkStatus(Output $output)
    {
        if ($this->isRunning()) {
            $output->writeln('RabbitMQ消费者正在运行 (PID: ' . $this->getPid() . ')');
        } else {
            $output->writeln('RabbitMQ消费者未运行');
        }
    }
    
    /**
     * 检查进程是否在运行
     */
    protected function isRunning()
    {
        $pid = $this->getPid();
        if (!$pid) {
            return false;
        }
        
        return posix_kill($pid, 0);
    }
    
    /**
     * 获取进程ID
     */
    protected function getPid()
    {
        if (file_exists($this->pidFile)) {
            return (int) file_get_contents($this->pidFile);
        }
        return null;
    }
    
    /**
     * 保存进程ID
     */
    protected function savePid($pid)
    {
        file_put_contents($this->pidFile, $pid);
    }
    
    /**
     * 清理PID文件
     */
    protected function cleanPidFile()
    {
        if (file_exists($this->pidFile)) {
            unlink($this->pidFile);
        }
    }
}